<script setup lang="tsx">
import { ref } from 'vue';
import { $t } from '@/locales';
import { SysemailsendrecordApi, type ApiStateInput, type ApiSysEmailSendRecordOut, type ApiSysEmailSendRecordQuery, type ApiUserOut, type ApiUserQuery } from '@/api-services';
import { feature, getAPI } from '@/axios-utils';
import { fetchTableQuery, useNetoTable, useTableOperate, useTableScroll } from '@/hooks/common/neto-table';
import { queryDone } from '@/utils/api';
import OperateModal from './modules/operate-modal.vue';
import EmailDetail from './modules/email-detail.vue';
import Search from './modules/search.vue';
import { ElButton, ElPopconfirm, ElTag } from 'element-plus';

const { tableWrapperRef, scrollConfig } = useTableScroll();


// 定义 apiFunc 为一个函数，接受参数并返回 Promise
const apiFunc = (params: ApiSysEmailSendRecordQuery) =>
  fetchTableQuery<ApiSysEmailSendRecordQuery, ApiSysEmailSendRecordOut>(params,
    (internalParams: ApiSysEmailSendRecordQuery) =>
      getAPI(SysemailsendrecordApi).getList(internalParams)
  );

const loadingStates = ref<Record<string, boolean>>({});
const {
  columns,
  columnChecks,
  tableSize,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useNetoTable({
  apiFn: apiFunc,
  size: 'small',
  // apiFn:fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList),
  // apiFn: fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList.bind(getAPI(ApiuserserviceApi))),
  apiParams: {
    pageIndex: 1,
    pageSize: 10,
    keyWords: '',
    startDate: undefined,
    endDate: undefined
  },
  columns: () => [

    { type: 'selection', width: 48 },
    {
      prop: 'id',
      //dataIndex: 'id',
      label: 'id',
      minWidth: 230,
    },
    {
      prop: 'templateType',
      //dataIndex: 'templateType',
      label: $t('page.emailManage.emailSendRecord.templateType'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        if (record.templateType === null) {
          return '';
        }

        let tag = '';
        switch (record.templateType) {

          case 0:
            //会员注册
            tag = $t('page.emailManage.emailSendRecord.form.templateTypeEnum.placeholder');
            break;
          case 1001:
            //会员注册
            tag = $t('page.emailManage.emailSendRecord.form.templateTypeEnum.register');
            break;
          case 1002:
            //会员修改密码
            tag = $t('page.emailManage.emailSendRecord.form.templateTypeEnum.updatePwd');

            break;
          case 1003:
            //会员修改邮箱
            tag = $t('page.emailManage.emailSendRecord.form.templateTypeEnum.updateEmail');

            break;
          case 1004:
            //会员重置密码
            tag = $t('page.emailManage.emailSendRecord.form.templateTypeEnum.resetPwd');


            break;
        }
        return <ElTag type="success">{tag}</ElTag>
      }

    },
    {
      prop: 'subject',
      //dataIndex: 'subject',
      label: $t('page.emailManage.emailSendRecord.subject'),
      align: 'center',
      minWidth: 100
    },
    // {
    //   prop: 'content',
    //   //dataIndex: 'content',
    //   label: $t('page.emailManage.emailSendRecord.content'),
    //   align: 'center',
    //   minWidth: 100
    // },
    {
      prop: 'senderName',
      //dataIndex: 'senderName',
      label: $t('page.emailManage.emailSendRecord.senderName'),
      align: 'center',
      minWidth: 100,
      hide: true
    },
    {
      prop: 'senderEmail',
      //dataIndex: 'senderEmail',
      label: $t('page.emailManage.emailSendRecord.senderEmail'),
      align: 'center',
      minWidth: 100,
      hide: true
    },

    {
      prop: 'receiveName',
      //dataIndex: 'receiveName',
      //收件人
      label: $t('page.emailManage.emailSendRecord.receiveName'),
      align: 'center',
      minWidth: 100
    },

    {
      prop: 'receiveEmail',
      //dataIndex: 'receiveEmail',
      //收件邮箱
      label: $t('page.emailManage.emailSendRecord.senderName'),
      align: 'center',
      minWidth: 100
    },

    {
      prop: 'state',
      //dataIndex: 'state',
      //邮件发送状态
      label: $t('page.emailManage.emailSendRecord.state'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        switch (record.state) {
          case 0:
            // 未发送
            let tag = $t('page.emailManage.emailSendRecord.stateEnum.notSent')
            return <ElTag type="warning">{tag}</ElTag>
          case 1:
            //已发送
            let tag2 = $t('page.emailManage.emailSendRecord.stateEnum.hasBeenSent')
            return <ElTag type="success">{tag2}</ElTag>
          case 2:
            //发送失败
            let tag3 = $t('page.emailManage.emailSendRecord.stateEnum.failSent')
            return <ElTag type="danger">{tag3}</ElTag>
          default:
            return '';
        }
      }
    },

    {
      prop: 'sendNum',
      //dataIndex: 'sendNum',
      //发送次数
      label: $t('page.emailManage.emailSendRecord.sendNum'),
      align: 'center',
      minWidth: 100
    },

    {
      prop: 'sendMaxNum',
      //dataIndex: 'sendMaxNum',
      //最大发送次数
      label: $t('page.emailManage.emailSendRecord.sendMaxNum'),
      align: 'center',
      minWidth: 100
    },
    {
      prop: 'isVerCode',
      //dataIndex: 'isVerCode',
      //是否验证码
      label: $t('page.emailManage.emailSendRecord.isVerCode'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        if (record.isVerCode === null) {
          return '';
        }
        let tag = record.isVerCode == true ? $t('common.yesOrNo.yes') : $t('common.yesOrNo.no');
        if (record.isVerCode == true) {
          return <ElTag type="success" >{tag}</ElTag >
        } else {
          return <ElTag type="danger">{tag}</ElTag>
        }
      }
    },

    {
      prop: 'verCode',
      //dataIndex: 'verCode',
      //验证码
      label: $t('page.emailManage.emailSendRecord.verCode'),
      align: 'center',
      minWidth: 100
    },
    {
      prop: 'isUse',
      //dataIndex: 'isUse',
      //是否使用
      label: $t('page.emailManage.emailSendRecord.isUse'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        if (record.isUse === null) {
          return '';
        }
        let tag = record.isVerCode == true ? $t('common.yesOrNo.yes') : $t('common.yesOrNo.no');
        if (record.isVerCode == true) {
          return <ElTag type="success" >{tag}</ElTag >
        } else {
          return <ElTag type="danger">{tag}</ElTag>
        }
      }
    },

    {
      //创建时间
      prop: 'creationTime',
      //dataIndex: 'creationTime',
      label: $t('common.creationTime'),
      align: 'center',
      hide: true,
      minWidth: 150
    },
    {
      //创建人
      prop: 'creatorUserName',
      //dataIndex: 'creatorUserName',
      label: $t('common.creatorUserName'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    {
      //修改时间
      prop: 'updateTime',
      //dataIndex: 'updateTime',
      label: $t('common.updateTime'),
      align: 'center',
      hide: true,
      minWidth: 150
    },
    {
      //修改人
      prop: 'updateUserName',
      //dataIndex: 'updateUserName',
      label: $t('common.updateUserName'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    {
      prop: 'index',
      label: $t('common.action'),
      align: 'center',
      minWidth: 270,
      fixed: 'right',
      formatter: record => (
        <div class="flex-center gap-8px">
          <ElButton type="primary" plain size="small" onClick={() => handleShowEmailDetail(record.id!)}>
            {$t('common.detail')}
          </ElButton>
          <ElButton type="primary" plain size="small" onClick={() => edit(record.id!)}>
            {$t('common.edit')}
          </ElButton>
          <ElPopconfirm onConfirm={() => handleDelete(record.id!)} title={$t('common.confirmDelete')}>
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>
      )
    }
  ]
});

const isVisibleEmailDetail = ref(false);
const handleShowEmailDetail = (editId: number) => {
  editingId.value = editId;
  isVisibleEmailDetail.value = true;
};
const {
  isVisible,
  operateType,
  editingData,
  editingId,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
} = useTableOperate(data, getData);
const edit = (id: number) => {
  // console.log(id);
  handleEdit(id);
};
const handleDelete = async (id: number) => {
  const ids = [];

  // 提交请求
  const [err, res] = await feature(getAPI(SysemailsendrecordApi).batchDelete(id.toString()));

  queryDone(err, async () => {
    if (res?.data.data) {
      onDeleted();
    } else {
      window.$message?.error($t('common.failed'));
    }
  });
};
const handleBatchDeleted = async () => {
  if (checkedRowKeys.value == undefined || checkedRowKeys.value.length == 0) {
    return;
  }
  const ids = checkedRowKeys.value?.join(',');

  // 提交请求
  const [err, res] = await feature(getAPI(SysemailsendrecordApi).batchDelete(ids));

  queryDone(err, async () => {
    if (res?.data.data) {
      onBatchDeleted();
    } else {
      window.$message?.error($t('common.failed'));
    }
  });
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage"></Search>

    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.emailManage.emailSendRecord.title') }}</p>
          <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
            v-model:size="tableSize" :show-table-size="true" :loading="loading" @add="handleAdd"
            @delete="handleBatchDeleted" @refresh="getData" :show-add="false" />
        </div>
      </template>
      <div class="h-[calc(100%-50px)]">
        <ElTable v-loading="loading" height="100%" border class="sm:h-full" :data="data" row-key="id"
          @selection-change="checkedRowKeys = $event">
          <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
        </ElTable>
      </div>
      <div class="mt-20px flex justify-end">
        <ElPagination v-if="mobilePagination.total" layout="total,prev,pager,next,sizes" v-bind="mobilePagination"
          v-model:current-page="mobilePagination.currentPage" v-model:page-size="mobilePagination.pageSize" />
      </div>
      <OperateModal v-model:visible="isVisible" :operate-type="operateType" :edit-id="editingId"
        @submitted="getDataByPage" />
      <EmailDetail v-model:visible="isVisibleEmailDetail" :edit-id="editingId"></EmailDetail>
    </ElCard>
  </div>
</template>

<style scoped></style>
